using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(Image))]
public class GuideBase : MonoBehaviour
{
    protected Material material;
    protected Vector3 center;

    protected RectTransform target;

    protected Vector3[] targetCorners = new Vector3[4];

    protected virtual void Start()
    {
        material = transform.GetComponent<Image>().material;
        if(material == null)
        {
            throw new System.Exception("为获取到材质");
        }
    }

    public virtual void Guide(Canvas canvas, RectTransform target)
    {
        material = transform.GetComponent<Image>().material;

        this.target = target;

        //获取中心点
        target.GetWorldCorners(targetCorners);

        for (int i = 0; i < targetCorners.Length; i++)
        {
            targetCorners[i] = WorldToScreenPoint(canvas, targetCorners[i]);
        }

        center.x = targetCorners[0].x + (targetCorners[3].x - targetCorners[0].x) / 2;
        center.y = targetCorners[0].y + (targetCorners[1].y - targetCorners[0].y) / 2;
        material.SetVector("_Center", center);

        //width = (targetCorners[3].x - targetCorners[0].x) / 2;
        //height = (targetCorners[1].y - targetCorners[0].y) / 2;
        //material.SetFloat("_SliderX", width);
        //material.SetFloat("_SliderY", height);
    }

    public virtual void Guide(Canvas canvas, RectTransform target,float scale,float time)
    {

    }

    protected Vector2 WorldToScreenPoint(Canvas canvas, Vector3 world)
    {
        //世界坐标转屏幕坐标
        Vector2 screenPoint = RectTransformUtility.WorldToScreenPoint(canvas.worldCamera, world);
        Vector2 localPoint;
        //屏幕坐标转局部坐标
        RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.GetComponent<RectTransform>(), screenPoint, canvas.worldCamera, out localPoint);
        return localPoint;
    }
}
